package com.sz.util;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Properties;

public class Tool {

    /**
     * 获取xml文件的内容
     *
     * @param xmlFileName
     * @return
     */
    public static Element getRootElement(String xmlFileName, final String UPLOADDIR) {
        SAXReader reader = new SAXReader();
        Document doc = null;
        String dir = UPLOADDIR;

        try {
            File file = null;
            try {
                file = new File(dir + File.separator + xmlFileName);
            } catch (Exception e) {
                e.printStackTrace();
                file = new File(dir + xmlFileName);
            }
            doc = reader.read(file);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (doc == null) {
            return null;
        } else {
            return doc.getRootElement();
        }

    }



    /**
     * 初始化properties文件
     *
     * @param propertiesPath-文件路径
     * @param module-反射对象
     */
    public static void initProperties(String propertiesPath, Object module) {

        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(propertiesPath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Enumeration<?> enumeration = properties.propertyNames();// 得到配置文件的名字

        if (enumeration.hasMoreElements()) {

            Class<? extends Object> clazz = module.getClass();
            for (Method method : clazz.getMethods()) {
                if (method.getName().indexOf("set") == 0) {
                    String temp = method.getName().substring(3);
                    String key = ToolStr.indexCodeLowerCase(temp);
                    String value = properties.getProperty(key);
                    Method setMothod = null;
                    try {
                        setMothod = clazz.getMethod("set" + temp, String.class);
                        setMothod.invoke(module, value);
                    } catch (Exception e) {
                    }
                }
            }
        }

    }
}
